<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1100px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      :inline="true"
      label-width="auto"
    >
      <el-form-item label="房间名称" prop="roomName">
        <el-input v-model="formData.roomName" placeholder="请输入房间名称" :clearable="true" />
      </el-form-item>
      <el-form-item label="房间类型" prop="roomTypeId">
        <el-select v-model="formData.roomTypeId" placeholder="请选择房间类型" :clearable="true">
          <el-option
            v-for="dict in roomTypeList"
            :key="dict.id"
            :label="dict.typeName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼栋" prop="buildingId">
        <el-select v-model="formData.buildingId" placeholder="请选择楼栋" :clearable="true">
          <el-option
            v-for="dict in buildList"
            :key="dict.id"
            :label="dict.buildingName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房间朝向" prop="roomOrientation">
        <el-select v-model="formData.roomOrientation" placeholder="请选择房间朝向">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BED_ROOM_ORIENTATION)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房间面积" prop="roomArea">
        <InputNumber v-model="formData.roomArea" placeholder="请输入房间面积" type="decimal" />
      </el-form-item>
      <el-form-item label="床位数量" prop="bedNumber">
        <el-select
          v-model="formData.bedNumber"
          placeholder="请输入床位数量"
          :clearable="true"
          disabled
        />
      </el-form-item>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddBed">添加床位</el-button>
      <el-button @click="clickDeleteBed">删除床位</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.beds"
      save-key="BedInfoEdit"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    >
      <template #bedName="{ row }">
        <el-input class="!w-120px" v-model="row.bedName" />
      </template>
      <template #price="{ row }">
        <InputNumber class="!w-70px" v-model="row.price" type="decimal" />
      </template>
      <template #chargeType="{ row }">
        <el-select v-model="row.chargeType">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FEE_CHARGE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </template>
      <template #bedTypeId="{ row }">
        <el-select v-model="row.bedTypeId">
          <el-option
            v-for="dict in bedTypeList"
            :key="dict.id"
            :label="dict.typeName"
            :value="dict.id"
          />
        </el-select>
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="BedInfoEdit" lang="ts">
import * as BedInfoApi from '@/api/bed/bedInfo'
import * as BuildInfoApi from '@/api/bed/buildingInfo'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as BedInfoModel from '@/model/bed/bed/BedInfo'
import * as RoomInfoModel from '@/model/bed/room/RoomInfo'
interface BedinfoEdit extends BedInfoModel.BedInfo {
  operateType: string
}
interface RoomInfoEdit extends RoomInfoModel.RoomInfo {
  beds: BedinfoEdit[]
}

const { t } = useI18n()
const message = useMessage()
let formType = ''
const buildList = ref()
const roomTypeList = ref()
const bedTypeList = ref()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref<RoomInfoEdit>({
  id: undefined,
  roomName: '',
  roomTypeId: undefined,
  buildingId: undefined,
  roomOrientation: 1,
  roomArea: 0,
  bedNumber: 0,
  beds: []
})
const formRules = reactive({
  name: [{ required: true, message: '请输入房间名称', trigger: 'blur' }],
  roomTypeId: [{ required: true, message: '请选择房间类型', trigger: 'change' }],
  buildingId: [{ required: true, message: '请选择楼栋', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '床位名称',
    prop: 'bedName',
    slot: 'bedName'
  },
  {
    label: '价格',
    prop: 'price',
    slot: 'price'
  },
  {
    label: '收费方式',
    prop: 'chargeType',
    slot: 'chargeType'
  },
  {
    label: '床位类型',
    prop: 'bedTypeId',
    slot: 'bedTypeId'
  }
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  buildList.value = await BuildInfoApi.listQuery()
  roomTypeList.value = await BedInfoApi.listQueryRoomType()
  bedTypeList.value = await BedInfoApi.listQueryBedType()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BedInfoApi.getRoom(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    roomName: '',
    roomTypeId: undefined,
    buildingId: undefined,
    roomOrientation: 1,
    roomArea: 0,
    bedNumber: 0,
    beds: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.beds.length <= 0) {
    message.error('请添加至少一条床位信息')
    return
  }
  let uniqueBeds = Array.from(
    new Set(
      formData.value.beds.map((bed) => {
        return bed.bedName
      })
    )
  )
  if (uniqueBeds.length != formData.value.beds.length) {
    message.error('存在重复的床位信息')
    return
  }
  let isBedEmpty = false
  let isBedTypeEmpty = false
  formData.value.beds.forEach((bed) => {
    if (bed.bedName == '') isBedEmpty = true
    if (bed.bedTypeId == undefined) isBedTypeEmpty = true
  })
  if (isBedEmpty) {
    message.error('床位名称不能为空')
    return
  }
  if (isBedTypeEmpty) {
    message.error('床位类型不能为空')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RoomInfoEdit
    if (formType === 'create') {
      await BedInfoApi.roomCreate(data)
      message.success(t('common.createSuccess'))
    } else {
      await BedInfoApi.roomUpdate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = async (row) => {
  tableCurrentRow.value = row
}

const clickAddBed = () => {
  formData.value.beds.push({
    id: undefined,
    roomId: formType === 'create' ? undefined : formData.value.id,
    bedName: '',
    price: 0,
    bedTypeId: undefined,
    operateType: 'new',
    chargeType: 1
  })
  formData.value.bedNumber = formData.value.beds.length
}

const clickDeleteBed = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的床位')
    return
  }
  if (formType === 'create' || tableCurrentRow.value.id == '') {
    const index = formData.value.beds.indexOf(tableCurrentRow.value)
    formData.value.beds.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
  formData.value.bedNumber = formData.value.beds.length
}
</script>
